﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MySql.Data.MySqlClient;
using System.Data.Odbc;


using tag = functionService.tagWork;
using H = functionService.shorts;
using da = functionService.DATECOD;
using fr = HK.FiscalRegistrar.FiscalRegistrar;
using vv = functionService.serfun_city7;
using rz = functionService.serfun_city7.rz;
using nameCod = functionService.nameCod;

namespace ETALON
{
    enum modeList
    { 
        find,
        add, del, 
        edit, setgroup,
        copyGroup, cutGroup,
        pasteGroup, deleteGroup, filterGroup, readOnly, editParam 
    };
    public struct serverName 
    { 
    public const string localhost = "localhost",
     serverExp = "serverExp",
     Homekin = "Homekin";
    }
    public partial class listAnyEdit : Form
    {
        string filterBeforeEdit;
        functionService.prm_city  q; 
        //dll_rol.pro_listParam pr;
        //MySqlConnection conn;
        public delegate void funcd(object oCod);
        public delegate void funcd_add(object oCod, object oName, object whereCondition);
        public delegate void funcd_del(object oCod);
        public delegate void funcd_edt(object oCod, object oName);
        funcd foo;
        funcd_add fAdd; funcd_del fDel; funcd_edt fEdt;
        ArrayList ar; DataTable dt;
        public string sName, sCod, sText; int indexSelect; 
        string nameTable, schema, whereCondition;

        bool HasWhereCondition;
        bool HasDelegate;
        bool Has3Delegate;
        public ListViewItem[] iCOPY;

        public bool IsOK;
        ArrayList arFilters;

        public listAnyEdit(string sSQL, bool IsReadOnly)
        {
           // nameTable = nameTableOut; schema = schemaOut;
            string sql = sSQL; HasWhereCondition = false; Has3Delegate = false;
            InitializeComponent();
            q = new functionService.prm_city();
            q.con.setConn(q.tk(param.server_1));
            // q = new fs.prm("PLP");  //conn.setConn(serverName.localhost); 

            dt = q.selectAny(sql);
            ar = tableToArray(dt);
            sName = ""; sCod = ""; sText = ""; listBoxFill(ar);
            setMode(modeList.find);
            if (IsReadOnly) setMode(modeList.readOnly);
            HasDelegate = false;
            IsOK = false;
            toolStripStatusLabel1.Text = serverName.localhost;
            filterBeforeEdit = " ";

            arFilters = new ArrayList(); //arFilters.Add("нап"); arFilters.Add("тес"); arFilters.Add("смес"); arFilters.Add("торт"); arFilters.Add("торт");
            loadTagToArr();
        }
        public listAnyEdit(string schemaOut,  string nameTableOut, bool IsReadOnly)
        {
            nameTable = nameTableOut; schema = schemaOut; HasWhereCondition = false;
            string sql = string.Concat("SELECT * FROM  ",  schema,".", nameTable , ";");
            InitializeComponent();
            q = new functionService.prm_city(); 
            q.con.setConn(q.tk(param.server_1));
           // q = new fs.prm("PLP");
            
            //conn.setConn(serverName.localhost); 

            dt = q.selectAny(sql);
            ar = tableToArray(dt); sName = ""; sCod = ""; sText = ""; listBoxFill(ar);
            setMode(modeList.find);
            if (IsReadOnly) setMode(modeList.readOnly);
            HasDelegate = false;
            IsOK = false;
            toolStripStatusLabel1.Text = serverName.localhost ;
            filterBeforeEdit = " ";

            arFilters = new ArrayList(); //arFilters.Add("нап"); arFilters.Add("тес"); arFilters.Add("смес"); arFilters.Add("торт"); arFilters.Add("торт");
            loadTagToArr();
        }


        public listAnyEdit(string schemaOut, string nameTableOut, string whereConditionOut)
        {
            nameTable = nameTableOut; schema = schemaOut; whereCondition = whereConditionOut; HasWhereCondition = true ;
            string sql = string.Concat("SELECT * FROM  ", schema, ".", nameTable, " WHERE ", whereCondition, ";");
            InitializeComponent();
            q = new functionService.prm_city();
            q.con.setConn(q.tk(param.server_1));
             dt = q.selectAny(sql);
            ar = tableToArray(dt); sName = ""; sCod = ""; sText = ""; listBoxFill(ar);
            setMode(modeList.find);
            //if (IsReadOnly) setMode(modeList.readOnly);
            HasDelegate = false;
            IsOK = false;
            toolStripStatusLabel1.Text = serverName.localhost;
            filterBeforeEdit = " ";

            arFilters = new ArrayList(); //arFilters.Add("нап"); arFilters.Add("тес"); arFilters.Add("смес"); arFilters.Add("торт"); arFilters.Add("торт");
            loadTagToArr();
        }
        public listAnyEdit(funcd fo, string schemaOuto, string nameTableOuto, bool IsReadOnlyo)
            : this(schemaOuto, nameTableOuto, IsReadOnlyo)
        {
            foo = fo; HasDelegate = true ;
        }
        public listAnyEdit(funcd fo, string schemaOuto, string nameTableOuto, string WhereConditionOUT)
            : this(schemaOuto, nameTableOuto, WhereConditionOUT)
        {
            foo = fo; HasDelegate = true; 
        }
        public listAnyEdit(string schemaOuto, string nameTableOuto, string WhereConditionOUT, 
              funcd_add fAdd0, funcd_del fDel0, funcd_edt fEdt0)
            : this(schemaOuto, nameTableOuto, WhereConditionOUT)
        {
            Has3Delegate = true;
            fAdd = fAdd0; fDel = fDel0; fEdt = fEdt0;
        }
        public listAnyEdit(funcd fo, string schemaOuto, string nameTableOuto, string WhereConditionOUT,
             funcd_add fAdd0, funcd_del fDel0, funcd_edt fEdt0)
            : this(schemaOuto, nameTableOuto, WhereConditionOUT)
        {
            HasDelegate = true;   foo = fo; 
            Has3Delegate = true;  fAdd = fAdd0; fDel = fDel0; fEdt = fEdt0;
        }
        //////private void setConn()
        //////{
        //////    string ss = q.tk(1);
        //////    if (ss == SERV.KIN)
        //////    {
        //////        conn = new MySqlConnection("server=localhost;user id=muser; password=; database=city; pooling=false");
        //////    }
        //////    else if (ss == SERV.EXP)
        //////    {
        //////        conn = new MySqlConnection("server=serverExp;user id=muser; password=; database=city; pooling=false");
        //////    }
        //////    else if (ss == SERV.EMG)
        //////    {
        //////        conn = new MySqlConnection("server=Homekin;user id=muser; password=; database=city; pooling=false");
        //////    }
        //////    toolStripStatusLabel1.Text = ss;

            
        //////}

        #region  tableToArray listBoxFill RefreshListBoxWhithFilter
        private ArrayList tableToArray(DataTable dt)
        {
            ArrayList a = new ArrayList(); 
            foreach (DataRow r in dt.Rows)
            { a.Add(string.Concat(r[1], " (", r[0], ")")); } return a;
        }
        //private ArrayList viewToArray(DataView dv)
        //{
        //    ArrayList a = new ArrayList();
        //    foreach (DataRow r in dv)
        //    { a.Add(string.Concat(r[1], " (", r[0], ")")); } return a;
        //}
        private void listBoxFill(ArrayList ar)
        {
            listBox1.Items.Clear(); ar.Sort(); foreach (string ars in ar) listBox1.Items.Add(ars); 
        }
        private void RefreshListBoxWhithFilter(string skeyData)
        {
            listBox1.Items.Clear(); string sfilter = skeyData;  //stext+skeyData 
            ar.Sort();

            #region old
            //for (int i = 0; i < ar.Count; i++)
            //{
            //    scurrent = ar[i].ToString();
            //    //System.Windows.Forms.MessageBox.Show(scurrent + "=scurrent" + scurrent.IndexOf(sfilter).ToString()+ "=scurrent.IndexOf");

            //    if (scurrent.IndexOf(sfilter) != -1)
            //    {
            //        listBox1.Items.Add(scurrent);
            //    }
            //}
            #endregion

            string ss = "";
            foreach (string scurrent in ar) 
            {
                ss = scurrent.ToLower();
                if (ss.IndexOf(sfilter.ToLower()) != -1) { listBox1.Items.Add(scurrent); }
            }
        }
        #endregion
       
        #region ReadSelect
        private void readSelect()
        {

            sText = listBox1.Text; sName = readName(sText); sCod = readCod(sText);
            indexSelect = this.listBox1.SelectedIndex; textBox1.Text = sName; textBox1.SelectAll();
            putListSelect(sCod, sName, sText);
        }
        private void putListSelect(string cod, string name, string text)
        {
            q.put((int)param.listAnyEdit_cod_104, cod); 
            q.put((int)param.listAnyEdit_name_105, name); 
            q.put((int)param.listAnyEdit_text_106, text);
        }
        private string readName(string sText)
        {
            string s = sText, ss = "-"; int i; i = s.IndexOf("(") - 1;
            if (i > 0) { ss = s.Substring(0, i); } return ss;
        }
        private string readCod(string sText)
        {
            string s = sText, ss = "0"; int i, ii, il = s.Length; i = s.IndexOf("(") - 1; ii = il - (s.IndexOf("(") + 1) - 1;
            if (i > 0) { ss = s.Substring((s.IndexOf("(") + 1), ii); } return ss;
        }
        #endregion


        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            filterBeforeEdit = textBox1.Text;
            setMode(modeList.add); //m(q.tk(3));
        }
        private void setMode(modeList mm)  
        {
            string s = Convert.ToString((int)mm); q.put((int)param.listAnyEdit_modeFAED_103, s);
            if (mm == modeList.add) { listBox1.BackColor = Color.SteelBlue; listBox1.ForeColor = Color.White; }
            else if (mm == modeList.del) { listBox1.BackColor = Color.DarkRed; listBox1.ForeColor = Color.White; }
            else if (mm == modeList.edit) 
            { 
                listBox1.BackColor = Color.SeaGreen; listBox1.ForeColor = Color.White; 
            }
            else if (mm == modeList.find) 
            { 
                listBox1.BackColor = Color.White; listBox1.ForeColor = Color.Black; 
            }
            else if (mm == modeList.readOnly) 
            { 
                listBox1.BackColor = Color.White; listBox1.ForeColor = Color.Black;
                toolStripDropDownButton1.Enabled = false;
                toolStripDropDownButton2.Enabled = false;
                toolStripDropDownButton3.Enabled = false;
                toolStripDropDownButton4.Enabled = false;
                toolStripDropDownButton5.Enabled = false;
            }
            else if (mm == modeList.editParam && HasDelegate == true )
            {
                listBox1.BackColor = Color.Goldenrod; listBox1.ForeColor = Color.White;
            }
        }
        private void m(object o)
        {
            MessageBox.Show(o.ToString());
        }
        #region ADD_UPDATE_DEL
        private void SQL_DML_DELETE_Fromlist(int iCod)
        {
            string sql = string.Concat("DELETE FROM  ", schema, ".", nameTable, " WHERE cod = ", iCod, ";"); q.UpdateData(sql);
            if (Has3Delegate)
            {
                fDel(iCod);
            }
        }
        private void SQL_DML_INSERT_TolistMIR(string name)
        {
            string sqlscount = string.Concat("select count(*) as codm from  ", schema, ".", nameTable, ";");
            int icount = Convert.ToInt32(q.selectScalar(sqlscount));
            int im = 1, im0=1;
            if (icount > 0)
            {
                string sqlsc = string.Concat("select max(cod) as codm from  ", schema, ".", nameTable, ";");
                im0 = Convert.ToInt32(q.selectScalar(sqlsc));
                im =max_in_row(im0);
            }
            string sql = string.Concat("INSERT  ", schema, ".", nameTable, "(cod, name) VALUES (", im, ", '", name.Replace("(", "/").Replace(")", "/"), "');");
            //MessageBox.Show(string.Concat("before ", name, " ", im)); 
            q.UpdateData(sql);
            //MessageBox.Show(string.Concat("after ",name, " ", im));
            q.put((int)param.listAnyEdit_1_146, "1");
            q.put((int)param.listAnyEdit_addname_147, name);
            q.put((int)param.listAnyEdit_so_148, im.ToString());

        }
        private void SQL_DML_INSERT_Tolist(string name)
        {
            string sqlscount = string.Concat("select count(*) as codm from  ", schema, ".", nameTable, ";");
            int icount = Convert.ToInt32(q.selectScalar(sqlscount));
            int im = 1;
            if (icount > 0)
            {
                string sqlsc = string.Concat("select max(cod) as codm from  ", schema, ".", nameTable, ";");
                im = 1 + Convert.ToInt32(q.selectScalar(sqlsc));
            }
            string sql = string.Concat("INSERT  ", schema, ".", nameTable, "(cod, name) VALUES (", im, ", '", name.Replace("(", "/").Replace(")", "/"), "');"); 
            //MessageBox.Show(string.Concat("before ", name, " ", im)); 
            q.UpdateData(sql);
            //MessageBox.Show(string.Concat("after ",name, " ", im));
                   q.put((int)param.listAnyEdit_1_146, "1");
                   q.put((int)param.listAnyEdit_addname_147, name);
                   q.put((int)param.listAnyEdit_so_148, im.ToString());
                 
        }
        int max_in_row(string  whereCondition)
        {
            string sql = string.Concat("SELECT cod, 0 AS cod123 FROM ", schema, ".", nameTable, " WHERE ", whereCondition, " order by COD;");
            DataTable dt = q.selectAny(sql); int i = 1, r = 0, rf = 1; bool br = false;

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                r = H.i(dt.Rows[j][0]); if (i == r) { i++; } else { rf = i; br = true; break; }
            }

            if (br) return rf; else return rf + 1;
        }
        int max_in_row(int max_end)
        {
            string sql = string.Concat("SELECT cod, 0 AS cod123 FROM ", schema, ".", nameTable, " WHERE COD<", max_end, " order by COD;");
            DataTable dt = q.selectAny(sql); int i = 1, r = 0, rf = 1; bool br = false;

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                r = H.i(dt.Rows[j][0]); if (i == r) { i++; } else { rf = i; br = true ; break; }
            }

            if (br) return rf; else return rf + 1;
        }
        int max_in_row()
        {
            int max_end = 1000;
            string sql = string.Concat("SELECT cod, 0 AS cod123 FROM ", schema, ".", nameTable, " WHERE COD<", max_end, " order by COD;");
            DataTable dt = q.selectAny(sql); int i = 1, r = 0, rf = 1; bool br = false;

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                r = H.i(dt.Rows[j][0]); if (i == r) { i++; } else { rf = i; br = true; break; }
            }

            if (br) return rf; else return rf + 1;
        }
        private void SQL_DML_INSERT_Tolist(string name, string whereCondition)
        {
            string sqlscount = string.Concat("select count(*) as codm from  ", schema, ".", nameTable, " WHERE ", whereCondition, ";");
            int icount = Convert.ToInt32(q.selectScalar(sqlscount));
            int im = 1;
            if (icount > 0)
            {
                string sqlsc = string.Concat("select max(cod) as codm from  ", schema, ".", nameTable, " WHERE ", whereCondition, ";");
                im = 1 + Convert.ToInt32(q.selectScalar(sqlsc));
            }

            string sql = string.Concat("INSERT  ", schema, ".", nameTable, "(cod, name) VALUES (", im, ", '", name.Replace("(","/").Replace(")","/"), "');");

            if (Has3Delegate) fAdd(im, name.Replace("(", "/").Replace(")", "/"), whereCondition);
            
            //MessageBox.Show(string.Concat("before ", name, " ", im)); 
            q.UpdateData(sql);
            //MessageBox.Show(string.Concat("after ",name, " ", im));
            q.put((int)param.listAnyEdit_1_146, "1");
            q.put((int)param.listAnyEdit_addname_147, name);
            q.put((int)param.listAnyEdit_so_148, im.ToString());

        }
        private void SQL_DML_INSERT_TolistMIR(string name, string whereCondition)
        {
            string sqlscount = string.Concat("select count(*) as codm from  ", schema, ".", nameTable, " WHERE ", whereCondition, ";");
            int icount = Convert.ToInt32(q.selectScalar(sqlscount));
            int im = 1;
            if (icount > 0)
            {
                im = max_in_row(whereCondition);
            }

            string sql = string.Concat("INSERT  ", schema, ".", nameTable, "(cod, name) VALUES (", im, ", '", name.Replace("(", "/").Replace(")", "/"), "');");

            if (Has3Delegate) fAdd(im, name.Replace("(", "/").Replace(")", "/"), whereCondition);

            //MessageBox.Show(string.Concat("before ", name, " ", im)); 
            q.UpdateData(sql);
            //MessageBox.Show(string.Concat("after ",name, " ", im));
            q.put((int)param.listAnyEdit_1_146, "1");
            q.put((int)param.listAnyEdit_addname_147, name);
            q.put((int)param.listAnyEdit_so_148, im.ToString());

        }
        private void SQL_DML_UPDATE_List(int iCod, string name)
        {
            string sql = string.Concat("UPDATE  ", schema, ".", nameTable, " SET  name = '", name, "' WHERE cod = ", iCod, ";"); q.UpdateData(sql);
            if (Has3Delegate)
            {
                fEdt(iCod, name);
            }
        }

        //public void UpdateData(string strSQL_DML)  {
        //    MySqlCommand cmd = q.con.cnn.CreateCommand(); cmd.CommandText = strSQL_DML; cmd.ExecuteNonQuery();
            
        //}
        
        #endregion

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            setMode(modeList.del ); 
        }
        private void toolStripDropDownButton4_Click(object sender, EventArgs e)
        {
            setMode(modeList.editParam);
        }
        private void toolStripDropDownButton3_Click(object sender, EventArgs e)
        {
            setMode(modeList.find );
        }
        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            sName = this.textBox1.Text; q.put((int)param.listAnyEdit_name_105, sName);
            string s = q.tk((int)param.listAnyEdit_modeFAED_103); int i = Convert.ToInt32(s);
            
            if((modeList)i == modeList.find  || (modeList)i == modeList.readOnly) 
            {RefreshListBoxWhithFilter(sName); }
            else if ((modeList)i == modeList.add) 
            {
                if (e.KeyValue == 13) 
                {
                    listBox1.Items.Clear();
                    //SQL_DML_INSERT_Tolist(sName, whereCondition);
                    SQL_DML_INSERT_TolistMIR(sName, whereCondition);
                    selectListIfEdit();// selectList();      
                }
            }
            else if ((modeList)i == modeList.del) { }
            else if ((modeList)i == modeList.edit) 
            {
                if (e.KeyValue == 13)
                {
                    int ii = Convert.ToInt32(q.tk((int)param.listAnyEdit_cod_104));
                    listBox1.Items.Clear();
                    SQL_DML_UPDATE_List(ii, sName);
                    selectListIfEdit();// selectList();
                    // RefreshListBoxWhithFilter(sName);
                }
            }
        }
        private void selectListIfEdit()
        {
            string ssql = string.Concat("SELECT * FROM  ", schema, ".", nameTable, ";");

            if (HasWhereCondition) ssql = string.Concat("SELECT * FROM  ", schema, ".", nameTable, " WHERE ", whereCondition ,";");

            DataTable dt =
                    q.selectAny(ssql);
            ar.Clear(); ar = tableToArray(dt);
            RefreshListBoxWhithFilter(filterBeforeEdit);
        }
        
         
        private void selectList()
        {

            string ssql = string.Concat("SELECT * FROM  ", schema, ".", nameTable, ";");

            if (HasWhereCondition) ssql = string.Concat("SELECT * FROM  ", schema, ".", nameTable, " WHERE ", whereCondition  ,";");
            
            DataTable dt =
                    q.selectAny(ssql);
            ar.Clear(); ar = tableToArray(dt); //RefreshListBoxWhithFilter(filterBeforeEdit);
        }
        private void listBox1_MouseUp(object sender, MouseEventArgs e)
        {
            readSelect();
            modeList mo = (modeList)Convert.ToInt32(q.tk((int)param.listAnyEdit_modeFAED_103));
            selectIfMode(mo);
        }
        private void selectIfMode(modeList mm)
        {
            readSelect();
            if (mm == modeList.readOnly) { mm = modeList.find; }
            if (mm == modeList.add) 
            {
                textBox1.Text = sName;
                if (HasWhereCondition == false)
                { 
                    //SQL_DML_INSERT_Tolist(sName);
                    SQL_DML_INSERT_TolistMIR(sName);
                }
                else 
                { 
                //    SQL_DML_INSERT_Tolist(sName, whereCondition);
                    SQL_DML_INSERT_TolistMIR(sName, whereCondition);
                }
                 
                
                selectList();
            }
            else if (mm == modeList.del) 
            {
                int ic = Convert.ToInt32(q.tk((int)param.listAnyEdit_cod_104));
                textBox1.Text = sName;
                SQL_DML_DELETE_Fromlist(ic); //m(ic);
                if (Has3Delegate) fDel(sCod);
                //selectList();
                selectListIfEdit();
            }
            else if (mm == modeList.edit)
            {
                textBox1.Text = sName;
            }
            else if (mm == modeList.find )
            {
                IsOK = true;
                this.Close();
            }
            else if (mm == modeList.editParam )
            {
                foo(sCod);
            }
        }
      
        private void toolStripDropDownButton5_Click(object sender, EventArgs e)
        {
            filterBeforeEdit = textBox1.Text;
            setMode(modeList.edit); 
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripDropDownButton6_Click(object sender, EventArgs e)
        {
            functionService.prm plp = new functionService.prm("PLP");
            userHK_grid.FormGRID fgr = new userHK_grid.FormGRID(string.Concat("SELECT * FROM ", nameTable, ";"), schema, plp.tk((int)param.server_1));
            fgr.ShowDialog();
        }
        private void loadTagToArr()
        {
            arFilters.Clear();
            string stag = q.tk(62);
         string[]at =   functionService.tagWork.readTAG_ToArray(stag);
         for (int j = 0; j < at.Length; j++)
         {
             arFilters.Add(at[j]);
         }
        }
        private void textBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            city7.lists.FormFilters f = new city7.lists.FormFilters();
            f.ShowDialog();
            if (f.IsOk)
            {
                textBox1.Text = f.valueSelect;
                sName = textBox1.Text;
                
                RefreshListBoxWhithFilter(sName);
            }
        }
    }
}
